package cn.qianxun.meta.quartz.controller;


import cn.qianxun.meta.common.core.dto.RowsData;
import cn.qianxun.meta.quartz.service.IXxlJobInfoService;
import cn.qianxun.meta.quartz.service.IXxlJobLogService;
import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.model.LogParam;
import com.xxl.job.core.biz.model.LogResult;
import com.xxl.job.core.biz.model.ReturnT;
import cn.qianxun.meta.common.core.domain.Result;
import cn.qianxun.meta.quartz.core.scheduler.XxlJobScheduler;
import cn.qianxun.meta.quartz.domain.XxlJobLog;
import cn.qianxun.meta.quartz.dto.JobLogClearDTO;
import cn.qianxun.meta.quartz.dto.XxlJobLogQueryDTO;
import cn.qianxun.meta.quartz.vo.XxlJobLogVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author fuzhilin
 * @Date 2023/9/8 16:57
 * @Description
 */
@Tag(name = "任务日志管理")
@RestController
@RequestMapping("/web/v1/jobLog")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class XxlJobLogController {

    private final IXxlJobLogService iXxlJobLogService;


    private final IXxlJobInfoService iXxlJobInfoService;

    /**
     * 任务日志列表
     */
    //@SaCheckPermission("web:v1:jobLog:list")
    @PostMapping("/list")
    public Result<RowsData<XxlJobLogVO>> getXxlJobLogs(@RequestBody XxlJobLogQueryDTO queryVO) {
        return Result.success("查询成功", iXxlJobLogService.getXxlJobLogs(queryVO));
    }

    /**
     * 查看执行日志
     */
    //@SaCheckPermission("web:v1:jobLog:logDetail")
    @GetMapping("/logDetail/{logId}")
    public ReturnT<LogResult> logDetail(@PathVariable("logId") String logId) {
        XxlJobLog jobLog = iXxlJobLogService.getById(logId);
        try {
            ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(jobLog.getExecutorAddress());
            ReturnT<LogResult> logResult = executorBiz.log(new LogParam(jobLog.getTriggerTime().getTime(), jobLog.getId(), 1));
            if (logResult.getContent() != null && logResult.getContent().getFromLineNum() > logResult.getContent().getToLineNum()) {
                if (jobLog.getHandleCode() > 0) {
                    logResult.getContent().setEnd(true);
                }
            }
            return logResult;
        } catch (Exception e) {
            return new ReturnT<LogResult>(ReturnT.FAIL_CODE, e.getMessage());
        }

    }

    /**
     * 清理执行日志
     */

    @PostMapping("/clearLog")
    public Result clearLog(@RequestBody JobLogClearDTO jobLogClearDTO) {
        String[] logs = jobLogClearDTO.getLogIds();
        List<String> logIds = Arrays.stream(logs).collect(Collectors.toList());
        if (logIds != null && logIds.size() > 0) {
            iXxlJobLogService.clearLog(logIds);
        }
        return Result.success("操作成功");
    }


}

